import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import AutoImport from 'unplugin-auto-import/vite'; //自动导入组件
import Components from 'unplugin-vue-components/vite';
import { AntDesignVueResolver } from "unplugin-vue-components/resolvers";
import tailwindcss from "@tailwindcss/vite";
import browserslist from 'browserslist';
import {browserslistToTargets} from 'lightningcss';

const __dirname = dirname( fileURLToPath( import.meta.url ) );
const VITE_API_URL = 'http://local.thinkphp.com/index.php/api';
// https://vitejs.dev/config/
export default defineConfig( {
	plugins : [
		// 引入 vue
		vue(),
		tailwindcss(),
		// 按需引入组件
		Components( {
			resolvers : [
				AntDesignVueResolver( {
					importStyle : false,
				} )
			]
		} ),
		// 自动导入组件
		// https://github.com/unplugin/unplugin-auto-import
		AutoImport( {
			imports : [
				'vue',
				'vue-router',
				'pinia',
				'vue-i18n',
				'@vueuse/core',
			],
			dts : 'types/auto-imports.d.ts',
			dirs : [ 'src/hooks', 'src/stores', 'src/utils', ],
		} ),
	],
	server : {
		base : '/',
		publicDir : resolve( __dirname, './dist' ),
		assetsInclude : resolve( __dirname, './src/assets' ),
		https : false,// 是否启用 https
		host : true,// 是否开启本地 ip 访问
		port : 8080,// 端口号
		// open : true,// 启动项目后是否自动打开浏览器
		cors : true,// 是否允许跨域
		// 设置代理
		proxy : {
			'/api' : {
				target : VITE_API_URL,
				changeOrigin : true,
				rewrite : ( path ) => path.replace( /^\/api/, '' ),
			}
		}
	},
	build : {
		// 启用 Tree-shaking 和压缩
		minify : 'esbuild',
		rollupOptions : {
			input : {
				main : resolve( __dirname, 'index.html' )
			},
			output : {
				manualChunks : {
					// 按需拆分代码包
					vue : [ 'vue', 'vue-router', 'pinia', 'axios' ],
					antd : [ 'ant-design-vue' ]
				}
			}
		},
		// 开启 Gzip/Brotli 压缩
		assetsCompression : {
			algorithm : 'brotliCompress',
			options : {}
		},
		cssMinify : 'lightningcss',
	},
	resolve : {
		alias : {
			'@' : resolve( __dirname, 'src' ),
			'@assets' : resolve( __dirname, 'src/assets' ),
			'@components' : resolve( __dirname, 'src/components' ),
			'@views' : resolve( __dirname, 'src/views' ),
			'@utils' : resolve( __dirname, 'src/utils' ),
			'@stores' : resolve( __dirname, 'src/stores' ),
			'@hooks' : resolve( __dirname, 'src/hooks' ),
			'@api' : resolve( __dirname, 'src/api' ),
			'@data' : resolve( __dirname, 'src/data' ),
		}
	},
	css : {
		transformer : 'lightningcss',
		lightningcss : {
			targets: browserslistToTargets(browserslist('>= 0.25%'))
		}
	}
} );


